package com.such.kit.datacast;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Set;

public class CastMoney {

	private static final String[] numbers = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
	/** unitSystem：单位进制，处理时将 number * 100，按（数字位数 - 1）作下标取单位 */
	private static final String[] unitSystems = {"分", "角", "圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾", "佰", "仟"};
	/** specialUnitIndex：特殊单位位置 */
	private static final Set<Integer> specialUnitIndexs = new HashSet<Integer>();
    private static final String negative = "（负数）";
    private static final String whole = "整";
    static {
    	specialUnitIndexs.add(2); // 元
    	specialUnitIndexs.add(6); // 万
    	specialUnitIndexs.add(10); // 亿
    	specialUnitIndexs.add(14); // 兆
    }

	/**
	 * <pre>
	 * 数字转换为大写数字
	 * </pre>
     * @param number 需转换的数字
	 * @return 大写数字
	 */
	public static String numberToChinese(BigDecimal number) {
        StringBuffer chinese = new StringBuffer();
		int signum = number.signum();
		if (signum == 0) {
			chinese.append(numbers[0]).append(unitSystems[0]).append(whole);
		} else {
			number = number.abs(); // 取绝对值
			number = number.movePointRight(2); // 移动小数点，既 * 100
			number = number.setScale(0, BigDecimal.ROUND_HALF_UP); // 四舍五入
			String value = number.toString(); // 去 long
			int valueLen = value.length();
			boolean addZero = false;
			if (signum == -1) {
				chinese.append(negative); // 添加负号
			}
			for (int i = 0; i < valueLen; i++) {
				int v = value.charAt(i) - '0'; // 转换为 int 类型
				int unitIndex = valueLen - i - 1;
				if (v == 0) {
					addZero = true;
					if (specialUnitIndexs.contains(unitIndex)) {
						addZero = false;
						chinese.append(unitSystems[unitIndex]);
					}
				} else {
					if (addZero) {
						addZero = false;
						chinese.append(numbers[0]);
					}
					chinese.append(numbers[v]).append(unitSystems[unitIndex]);
				}
				if (i == valueLen - 1 && v == 0) {
					// 有“分”位则不添加“整”
					chinese.append(whole);
				}
			}
		}
		return chinese.toString();
	}

	/**
	 * <pre>
	 * 为数字添加千位符
	 * </pre>
	 * @param number 需添加的数字
	 * @return 千位符数字
	 */
	public static String addThousandSeparator(BigDecimal number) {
		return NumberFormat.getNumberInstance().format(number);
	}

}
